/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* MpmProjectSuperviseService
* 项目督办
*
* 修改纪录
* 2021-07-28 版本：1.0 wudaliang 创建。
* @version 版本：1.0
* @author 作者：wudaliang
* 创建日期：2021-07-28
*/
package com.topscomm.mpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.*;
import com.topscomm.cbo.service.ICboApprovalFlowInsService;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboExcelImportConfigService;
import com.topscomm.cbo.service.impl.CboOrgService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.MpmSystemConst.MpmSuperviseObjectType;
import com.topscomm.mpm.MpmSystemConst.ProgressState;
import com.topscomm.mpm.service.IMpmPMOStandardizationRecordService;
import com.topscomm.pub.util.*;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.TapService;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.MpmDatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectSuperviseService;
import com.topscomm.mpm.service.impl.auto.MpmProjectSuperviseServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "mpmProjectSuperviseService")
@Scope(value = "singleton")
public class MpmProjectSuperviseService extends MpmProjectSuperviseServiceAuto implements IMpmProjectSuperviseService {


	@Autowired
	private MpmProjectService mpmProjectService;

	@Autowired
	private CboUserService cboUserService;

	@Autowired
	private CboOrgService cboOrgService;

	@Autowired
	private CboDeptService cboDeptService;

	@Autowired
	private MpmProjectMilepostService mpmProjectMilepostService;

	@Autowired
	private ICboMessageAppService cboMessageAppService;

	@Autowired
	private IMpmPMOStandardizationRecordService pmoStandardizationRecordService;
	@Autowired
	private ICboApprovalNodeInsService cboApprovalNodeInsService;

	// 3天的毫秒数
	private static final long ThreeDays = 1000L*60*60*24*3;



	FlowDatacodeCache flowDatacodeCache=new FlowDatacodeCache();
	DatacodeCache datacodeCache = new DatacodeCache();
	protected List<Map<String,Object>> flowidList=new ArrayList();

	@Autowired
	private ICboApprovalFlowInsService cboApprovalFlowInsService;


	/**
	 * @Description:   转换出查询督办报表SQL语句
	 * @Author:         wuyuyang
	 * @Return:         java.lang.String
	 * @exception:
	 * @Date:           17/3/2023 下午3:49
	 * @Version:        1.0
	 **/
	public String spellListNewSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("1 = 1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("startDate")) {
			String value = paraMap.get("startDate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and publishtime >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("endDate")) {
			String value = paraMap.get("endDate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and publishtime <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		// 项目等级
		if (paraMap.containsKey("projectlevel")) {
			String value = paraMap.get("projectlevel").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectlevel in ({0})", value);
		}
		// 项目所属省份
		if (paraMap.containsKey("deptcommoncode")) {
			String value = paraMap.get("deptcommoncode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcommoncode in ({0}) ", value);
		}
		return sql.toString();
	}

	/**
	 * @author: wudaliang
	 * @date: 2021-07-28
	 * @param entity
	 * @throws ServiceException
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
			String format = simpleDateFormat.format(new Date());
			String flowcode = docNo.substring(docNo.length() - 3);
			format=format+flowcode;
			entity.setValue(MpmProjectSuperviseEntity.FieldSupervisecode,format);
			entity.setValue(MpmProjectSuperviseEntity.FieldDocno, docNo);
		}
	}

	@Override
	protected void beforeSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
		super.beforeSubmit(entity, sessionUserBean);
		MpmProjectSuperviseEntity mpmProjectSuperviseEntity = (MpmProjectSuperviseEntity) entity;
		this.flowidList= flowDatacodeCache
			.getApprovalFlowListMap("ApprovalFlow_MpmProjectSupervise",
				mpmProjectSuperviseEntity.getApplyusercode(), "sortcode");
		if(flowidList.size()>0){
			mpmProjectSuperviseEntity.setFlowid(ConvertUtil.convertToLong(flowidList.get(0).get("id")));
		}else{
			throw new ServiceException("没有匹配的审批流，请联系管理员！");
		}
	}


	/**
	 * @author: wudaliang
	 * @date: 2021-07-30
	 * @description: 督办状态检查
	 * @return: void
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void ProjectSuperviseCheckJob() {
		StringBufferProxy sql = new StringBufferProxy();
		// 查询处于审批中状态,超过督办期限的督办单
		sql.appendSingle(" STATE = 1 and {0} > {1} ", SQLAdapter.toChar(SQLAdapter.getDate() + ",'yyyy-mm-dd'"),
				SQLAdapter.toChar(MpmProjectSuperviseEntity.FieldSuperviseperiod + ",'yyyy-mm-dd'"));
		List<MpmProjectSuperviseEntity> mpmProjectSuperviseEntities = this.queryByWhere(sql.toString());
		if (mpmProjectSuperviseEntities.isEmpty()) {
			return;
		}
		List<BasicEntity> overDueSuperviseList = new ArrayList<BasicEntity>();
		for (MpmProjectSuperviseEntity mpmProjectSuperviseEntity : mpmProjectSuperviseEntities) {
			// 审批流程超过3天则置为超期
			mpmProjectSuperviseEntity.setSupervisestate("1");
			overDueSuperviseList.add(mpmProjectSuperviseEntity);
		}
		this.updateBatch(overDueSuperviseList);
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2021-12-1
	 * @description:查询超期里程碑及任务
	 * @return: List<Map<String, Object>>
	 * @modify:
	 */
	private List<Map<String, Object>> getOverdueMilePost() {
		StringBufferProxy sql = new StringBufferProxy();
		// 查询今天是超期第一天的里程碑及任务
		sql.appendSingle("TO_CHAR({0} + 1, 'yyyy-MM-dd') = TO_CHAR(SYSDATE, 'yyyy-MM-dd') AND {1} = '0' AND ENABLED = 1",
				MpmProjectMilepostEntity.FieldPlanfinishtime,
				MpmProjectMilepostEntity.FieldMilepoststate);
		List<Map<String, Object>> milePostList = mpmProjectMilepostService.queryMapByWhere(sql.toString());
		if (milePostList.isEmpty()) {
			return null;
		}
		sql.clear();
		List<Map<String, Object>> resultMap = new ArrayList<>();
		String milepostCodes = milePostList.stream().map(item -> ConvertUtil.convertToString(item.get(MpmProjectMilepostEntity.FieldMilepostcode)))
				.collect(Collectors.joining("','", "'", "'"));
		// 查询督办表是否存在超期里程碑及任务的督办单
		sql.appendSingle("{0} in ({1}) and {2} = '2' and enabled = '1'", MpmProjectSuperviseEntity.FieldSuperviseobjectcode, milepostCodes,
				MpmProjectSuperviseEntity.FieldSuperviseobjecttype);
		List<Map<String, Object>> superviseEntities = this.queryMapByWhere(sql.toString());
		// 若不存在督办单则把全部超期里程碑及任务返回
		if (superviseEntities.isEmpty()) {
			return milePostList;
		}
		// 若存在督办单，把没有督办单的超期里程碑及任务返回
		Map<String, List<Map<String, Object>>> superviseMap = superviseEntities.stream().collect(
				Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get(MpmProjectSuperviseEntity.FieldSuperviseobjectcode))));
		for (Map<String, Object> milepost : milePostList) {
			String milepostCode = ConvertUtil.convertToString(milepost.get(MpmProjectMilepostEntity.FieldMilepostcode));
			if (!superviseMap.containsKey(milepostCode) || !checkSuperviseList(superviseMap.get(milepostCode),"2")) {
				resultMap.add(milepost);
			}
		}
		return resultMap;
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2021-11-30
	 * @description:查询超期项目
	 * @return: List<Map<String, Object>>
	 * @modify:
	 */
	private List<Map<String, Object>> getOverdueProject() {
		StringBufferProxy sql = new StringBufferProxy();
		// 查询今天是超期第一天的项目
		sql.appendSingle(" TO_CHAR({0} + 1, 'yyyy-MM-dd') = TO_CHAR(SYSDATE, 'yyyy-MM-dd') AND {1} = '1' AND ENABLED = 1 ",
				MpmProjectEntity.FieldPlanenddate,
				MpmProjectEntity.FieldProjectstate);
		List<Map<String, Object>> projectList = mpmProjectService.queryMapByWhere(sql.toString());
		if (projectList.isEmpty()) {
		    return null;
		}
		sql.clear();
		List<Map<String, Object>> resultMap = new ArrayList<>();
		String projectCodes = projectList.stream().map(item -> ConvertUtil.convertToString(item.get("projectcode")))
				.collect(Collectors.joining("','", "'", "'"));
		// 查询督办表是否存在超期项目的督办单
		sql.appendSingle("{0} in ({1})", MpmProjectSuperviseEntity.FieldProjectcode, projectCodes);
		List<Map<String, Object>> superviseEntities = this.queryMapByWhere(sql.toString());
		// 若不存在督办单则把全部超期项目返回
		if (superviseEntities.isEmpty()) {
			return projectList;
		}
		// 若存在督办单，把没有督办单的超期项目返回
		Map<String, List<Map<String, Object>>> superviseMap = superviseEntities.stream().collect(
				Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get("projectcode")))
		);
		for (Map<String, Object> project : projectList) {
			String projectCode = ConvertUtil.convertToString(project.get("projectcode"));
			if (!superviseMap.containsKey(projectCode) || !checkSuperviseList(superviseMap.get(projectCode),"1")) {
				resultMap.add(project);
			}
		}
		return resultMap;
	}

    /**
     * @author: heyiheng
     * @date: 2023-03-16
     * @description:重写导入方法处理历史数据
     * @return: Int
     * @modify:
     */
	@Transactional(rollbackFor = Exception.class)
	public int executeImportExcel(Map<String, Object> paraMap, File attachFile) {
		String tableName = ConvertUtil.convertToString(paraMap.get("tableName"));
		if (tableName.length() == 0) {
			throw new ServiceException("请联系管理员配置数据库表");
		}
		CboExcelImportConfigService configService = (CboExcelImportConfigService) SpringUtil
				.getBean("cboExcelImportConfigService");
		List<CboExcelImportConfigEntity> listConfig = configService.queryByWhere("tablename='" + tableName + "'");
		if (listConfig == null || listConfig.size() < 1)
			throw new ServiceException("没有维护excel导入配置，表名为：" + tableName);
		// excel有效起始行
		int importStartRow = ConvertUtil.convertToInt(listConfig.get(0).getStartrow());
		// 导入字段映射关系json格式
		String importFields = listConfig.get(0).getRelationships();
		// 必填字段
		String requiredFields = listConfig.get(0).getRequiredfields();
		// 填充数据
		String expandJsonDate = listConfig.get(0).getSupplement();
		// 转换字段
		String convertFields = listConfig.get(0).getConvertfields();
		Map<String, String> convertFieldsMap = (Map<String, String>) JSONUtil.parseJSONString(convertFields);
		// 唯一字段
		String uniqueFields = listConfig.get(0).getUniquefields();
		// 字段描述
		String descFields = listConfig.get(0).getDescfields();
		Map<String, String> fieldDescMap = (Map<String, String>) JSONUtil.parseJSONString(descFields);
//		// 读取业务数据
		List<Map<String, String>> listDataMap;
		try {
			listDataMap = OfficeOperateUtil.parseExcel(attachFile, attachFile.getName(), importFields, importStartRow);
		} catch (Exception e) {
			throw new ServiceException("excel读取失败");
		}
		// 转换字段
		this.convertExcelData(listDataMap, convertFieldsMap);
//		// 自定义输入处理
//		this.expandInputExcelData(listDataMap, paraMap);
//		// 扩展处理，可以重写接口，实现特殊处理
//		this.expandProcessExcelData(listDataMap);
//		// 与数据库校验，校验长度、数据库类型是否合法
//		this.checkDataBaseFieldValid(listDataMap, importStartRow);
//		// 必填项校验
//		this.checkDataRequired(listDataMap, requiredFields, fieldDescMap, importStartRow);
//		// 唯一性校验
//		this.checkDataUnique(listDataMap, uniqueFields, fieldDescMap, importStartRow);
//		// 处理补充数据
//		this.addDefaultData(expandJsonDate, listDataMap);
//		// 数据入库
//		this.executeInsertExcelData(listDataMap)
 		String docnoc = listDataMap.stream().map(e->ConvertUtil.convertToString(e.get("supervisecode"))).collect(Collectors.joining("','","'","'"));
 		List<String> queryFields = new ArrayList<String>();
 		String[] a = docnoc.split(",");
 		int length = a.length;
 		queryFields.add(MpmProjectSuperviseEntity.FieldSupervisecode);
		queryFields.add(MpmProjectSuperviseEntity.FieldId);
 		List<Map<String,Object>> mpmProjectSuplist = this.queryMapFieldsByWhere("supervisecode in ("+docnoc+")",queryFields);
		Map<String,String> mpmMaps = mpmProjectSuplist.stream().collect(Collectors.toMap(e->ConvertUtil.convertToString(e.get("supervisecode")),e->ConvertUtil.convertToString(e.get("id"))));
		List<Map<String,Object>> resultList = new ArrayList<>();
		listDataMap.forEach(temp->{
			Map<String, Object> newMap = new HashMap<>();
			newMap.put("id",mpmMaps.get(ConvertUtil.convertToString(temp.get("supervisecode"))));
			newMap.put("superviseendstate",temp.get("superviseendstate"));
			resultList.add(newMap);
		});
		queryFields.clear();
		queryFields.add(MpmProjectSuperviseEntity.FieldSuperviseendstate);
		queryFields.add(MpmProjectSuperviseEntity.FieldId);
		this.updateFieldsBatchMap(resultList,queryFields);
		return listDataMap.size();
	}

	/**
	 * @author: heyiheng
	 * @date: 2023-03-16
	 * @description:检查是否有超期项目且未审批完成的督办单 "1", 里程碑 “2”
	 * @return: Boolean
	 * @modify:
	 */
	private Boolean checkSuperviseList(List<Map<String, Object>> tempList, String checkFlag) {
		// 检查超期项目
		if ("1".equals(checkFlag)) {
			for(Map map: tempList) {
				if(MpmSuperviseObjectType.project.equals(map.get("superviseobjecttype")) && !ProgressState.finished.equals(map.get("state")) && !ProgressState.refused.equals(map.get("state"))) {
					return true;
				}
			}
		}
		// 检查超期里程碑
		if ("2".equals(checkFlag)) {
			for(Map map: tempList) {
				if(MpmSuperviseObjectType.milepost.equals(map.get("superviseobjecttype")) && !ProgressState.finished.equals(map.get("state")) && !ProgressState.refused.equals(map.get("state"))) {
					return true;
				}
			}
		}
		return false;
	}
    /**
     * @author: zhangjunyao
     * @date: 2021-12-1
     * @description:查询PMO人员信息
     * @return: List<CboUserEntity>
     * @modify:
     */
	private List<CboUserEntity> getPmoInfo(List<MpmPMOStandardizationRecordEntity> pmoEntities) {
        StringBufferProxy sql = new StringBufferProxy();
	    // 获取所有PMO的工号，查询全部PMO的人员信息
        String userCodes = pmoEntities.stream().map(item -> ConvertUtil.convertToString(item.getUsercode()))
				.collect(Collectors.joining("','", "'", "'"));
        sql.appendSingle("code in ({0})", userCodes);
        List<CboUserEntity> userEntities = cboUserService.queryByWhere(sql.toString());
        return userEntities;
    }

    /**
     * @author: zhangjunyao
     * @date: 2021-12-1
     * @description:查询PMO部门信息
     * @return: List<CboDeptEntity>
     * @modify:
     */
    private List<CboDeptEntity> getPmoDeptInfo(List<CboUserEntity> userEntities) {
        // 根据人员信息查询全部PMO所属部门
        String workDeptIds = userEntities.stream().map(item -> ConvertUtil.convertToString(item.getWorkdeptid()))
				.collect(Collectors.joining("','", "'", "'"));
        List<CboDeptEntity> deptEntities = cboDeptService.queryByIds(workDeptIds);
        return deptEntities;
    }

    /**
     * @author: zhangjunyao
     * @date: 2021-12-1
     * @description:查询PMO组织信息
     * @return: List<CboOrgEntity>
     * @modify:
     */
    private List<CboOrgEntity> getPmoOrgInfo(List<CboDeptEntity> deptEntities) {
        // 根据部门信息查询全部PMO所属组织
        String orgIds = deptEntities.stream().map(item -> ConvertUtil.convertToString(item.getOrgid()))
				.collect(Collectors.joining("','", "'", "'"));
        List<CboOrgEntity> orgEntities = cboOrgService.queryByIds(orgIds);
        return orgEntities;
    }

    /**
     * @author: zhangjunyao
     * @date: 2021-12-1
     * @description:封装超期项目督办单信息并提交审批
     * @return:
     * @modify:
     */
    private void setSuperviseForProjects(List<Map<String, Object>> overDueProjects,
			List<MpmPMOStandardizationRecordEntity> pmoEntities, Map<String, CboUserEntity> userMap,
			Map<String, CboDeptEntity> deptMap, Map<String, CboOrgEntity> orgMap, Date time) {
        if(CollectionUtils.isEmpty(overDueProjects)) {
			return;
		}
		// 给每个超期项目创建督办单并提交审批
		for (Map<String, Object> overDueProject : overDueProjects) {
			String deptcommoncode = ConvertUtil.convertToString(overDueProject.get("deptcommoncode"));
			String userCode = "";
			// 查询超期项目归属的PMO工号
			for (MpmPMOStandardizationRecordEntity pmoEntity : pmoEntities) {
				String chargeProvinces = pmoEntity.getChargedeptcommoncode();
				if (("," + chargeProvinces + ",").contains("," + deptcommoncode+ ",")) {
					userCode = pmoEntity.getUsercode();
					break;
				}
			}
			// 获取该超期项目对应的PMO信息
			CboUserEntity userEntity = userMap.get(userCode);
			CboDeptEntity deptEntity = deptMap.get(ConvertUtil.convertToString(userEntity.getWorkdeptid()));
			CboOrgEntity orgEntity = orgMap.get(ConvertUtil.convertToString(deptEntity.getOrgid()));
			// 添加督办单信息
			MpmProjectSuperviseEntity superviseEntity = new MpmProjectSuperviseEntity();
			superviseEntity.setSupervisename(overDueProject.get("projectname") + "督办单");
			superviseEntity.setSupervisetype("0");
			superviseEntity.setSuperviseobjecttype("1");
			superviseEntity.setProjectcode(ConvertUtil.convertToString(overDueProject.get("projectcode")));
			superviseEntity.setProjectname(ConvertUtil.convertToString(overDueProject.get("projectname")));
			superviseEntity.setSuperviseobject(ConvertUtil.convertToString(overDueProject.get("projectname")));
			superviseEntity.setSuperviseobjectcode(ConvertUtil.convertToString(overDueProject.get("projectcode")));
			superviseEntity.setResponsiblename(ConvertUtil.convertToString(overDueProject.get(MpmProjectEntity.FieldProjectmanager)));
			superviseEntity.setResponsiblecode(ConvertUtil.convertToString(overDueProject.get(MpmProjectEntity.FieldProjectmanagercode)));
			superviseEntity.setSuperviseperiod(time);
			superviseEntity.setSupervisereason("该项目已超期");
			superviseEntity.setSupervisedeptname(deptEntity.getName());
			superviseEntity.setSupervisedeptcode(deptEntity.getCode());
			superviseEntity.setSupervisepeople(userEntity.getName());
			superviseEntity.setSupervisepeoplecode(userEntity.getCode());
			superviseEntity.setSupervisestate("0");
			superviseEntity.setDeptname(deptEntity.getName());
			superviseEntity.setDeptcode(deptEntity.getCode());
			superviseEntity.setApplydeptname(deptEntity.getName());
			superviseEntity.setApplydeptcode(deptEntity.getCode());
			superviseEntity.setOrgname(orgEntity.getName());
			superviseEntity.setOrgcode(orgEntity.getCode());
			superviseEntity.setUsername(userEntity.getName());
			superviseEntity.setUsercode(userEntity.getCode());
			superviseEntity.setApplyusercode(userEntity.getCode());
			superviseEntity.setApplyusername(userEntity.getName());
			superviseEntity.setProjectmanager(ConvertUtil.convertToString(overDueProject.get(MpmProjectEntity.FieldProjectmanager)));
			superviseEntity.setProjectmanagercode(ConvertUtil.convertToString(overDueProject.get(MpmProjectEntity.FieldProjectmanagercode)));
			superviseEntity.setDocdate(new Date());
			superviseEntity.setSubmitdate(new Date());
			superviseEntity.setSendresource(1);
			// 督办表提交审批
			StringBufferProxy mainTitle = new StringBufferProxy();
			mainTitle.appendSingle("{0}{1}于{2}提交项目督办申请! ", deptEntity.getName(),
					userEntity.getName(), DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
			SessionUserBean sessionUserBean = new SessionUserBean();
			sessionUserBean.setUser(userEntity);
			sessionUserBean.setDept(deptEntity);
			sessionUserBean.setWorkDept(deptEntity);
			sessionUserBean.setOrg(orgEntity);
			sessionUserBean.setWorkOrg(orgEntity);
			//提交督办单据
			this.executeSubmit(superviseEntity, mainTitle.toString(), sessionUserBean);
		}
    }

	/**
	 * @author: zhangjunyao
	 * @date: 2021-12-2
	 * @description:根据超期里程碑及任务查询对应项目
	 * @return: Map<String, MpmProjectEntity>
	 * @modify:
	 */
	private Map<String, MpmProjectEntity> getProjectByMilePost(List<Map<String, Object>> overDueMilePosts) {
		StringBufferProxy sql = new StringBufferProxy();
		String projectCodes = overDueMilePosts.stream().map(item -> ConvertUtil.convertToString(item.get("projectcode")))
				.collect(Collectors.joining("','", "'", "'"));
		sql.appendSingle("projectcode in ({0})", projectCodes);
		List<MpmProjectEntity> projectEntities = mpmProjectService.queryByWhere(sql.toString());
		// 转为map类型
		Map<String, MpmProjectEntity> projectMap = projectEntities.stream().collect(Collectors.toMap(
				MpmProjectEntity::getProjectcode, mpmProjectEntity -> mpmProjectEntity, (v1, v2) -> v1));
		return projectMap;
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2021-12-10
	 * @description:对部门编码进行截取
	 * @return:String
	 * @modify:
	 */
	private String getPmoDeptCode(String deptCode) {
		String result = "";
		if (deptCode.contains("_")) {
			String[] deptCodes = deptCode.split("_");
			result = deptCodes[0] + "_" + deptCodes[1].substring(0, 2);
		} else {
			result = deptCode.substring(0, 4);
		}
		return result;
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2021-12-2
	 * @description:封装超期里程碑及任务督办单信息并提交审批
	 * @return:
	 * @modify:
	 */
    private void setSuperviseForMilePost(List<Map<String, Object>> overDueMilePosts,
			List<MpmPMOStandardizationRecordEntity> pmoEntities, Map<String, CboUserEntity> userMap,
			Map<String, CboDeptEntity> deptMap, Map<String, CboOrgEntity> orgMap, Date time) {
		if (CollectionUtils.isEmpty(overDueMilePosts)) {
			return;
		}
		// 获取超期里程碑及任务对应的项目，并转为map类型
		Map<String, MpmProjectEntity> projectMap = getProjectByMilePost(overDueMilePosts);
		// 给每个超期里程碑及任务创建督办单
		for (Map<String, Object> overDueMilePost : overDueMilePosts) {
			String projectCode = ConvertUtil.convertToString(overDueMilePost.get("projectcode"));
			MpmProjectEntity projectEntity = projectMap.get(projectCode);
			String deptcommoncode = projectEntity.getDeptcommoncode();
			String userCode = "";
			// 查询超期项目归属的PMO工号
			for (MpmPMOStandardizationRecordEntity pmoEntity : pmoEntities) {
				String chargeProvinces = pmoEntity.getChargeprovinces();
				if (("," + chargeProvinces + ",").contains("," + deptcommoncode + ",")) {
					userCode = pmoEntity.getUsercode();
					break;
				}
			}
			// 获取该超期项目对应的PMO信息
			CboUserEntity userEntity = userMap.get(userCode);
			CboDeptEntity deptEntity = deptMap.get(ConvertUtil.convertToString(userEntity.getWorkdeptid()));
			CboOrgEntity orgEntity = orgMap.get(ConvertUtil.convertToString(deptEntity.getOrgid()));
			// 添加督办单
			MpmProjectSuperviseEntity superviseEntity = new MpmProjectSuperviseEntity();
			superviseEntity.setSupervisename(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectMilepostEntity.FieldMilepostname))+"督办单");
            superviseEntity.setSupervisetype("0");
			superviseEntity.setSuperviseobjecttype("2");
			superviseEntity.setProjectcode(projectEntity.getProjectcode());
			superviseEntity.setProjectname(projectEntity.getProjectname());
			superviseEntity.setSuperviseobject(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectMilepostEntity.FieldMilepostname)));
			superviseEntity.setSuperviseobjectcode(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectMilepostEntity.FieldMilepostcode)));
			superviseEntity.setResponsiblename(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectMilepostEntity.FieldResponsible)));
			superviseEntity.setResponsiblecode(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectMilepostEntity.FieldResponsiblecode)));
			superviseEntity.setSuperviseperiod(time);
			superviseEntity.setSupervisereason("该里程碑及任务已超期");
			superviseEntity.setSupervisedeptname(deptEntity.getName());
			superviseEntity.setSupervisedeptcode(deptEntity.getCode());
			superviseEntity.setSupervisepeople(userEntity.getName());
			superviseEntity.setSupervisepeoplecode(userEntity.getCode());
			superviseEntity.setSupervisestate("0");
			superviseEntity.setDeptname(deptEntity.getName());
			superviseEntity.setDeptcode(deptEntity.getCode());
			superviseEntity.setApplydeptname(deptEntity.getName());
			superviseEntity.setApplydeptcode(deptEntity.getCode());
			superviseEntity.setOrgname(orgEntity.getName());
			superviseEntity.setOrgcode(orgEntity.getCode());
			superviseEntity.setUsername(userEntity.getName());
			superviseEntity.setUsercode(userEntity.getCode());
			superviseEntity.setApplyusercode(userEntity.getCode());
			superviseEntity.setApplyusername(userEntity.getName());
			superviseEntity.setProjectmanager(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectEntity.FieldProjectmanager)));
			superviseEntity.setProjectmanagercode(ConvertUtil.convertToString(overDueMilePost.get(MpmProjectEntity.FieldProjectmanagercode)));
			superviseEntity.setDocdate(new Date());
			superviseEntity.setSubmitdate(new Date());
			superviseEntity.setSendresource(1);
			// 督办单提交审批
			StringBufferProxy mainTitle = new StringBufferProxy();
			mainTitle.appendSingle("{0}{1}于{2}提交项目督办申请! ",deptEntity.getName(),
					userEntity.getName(), DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
			SessionUserBean sessionUserBean = new SessionUserBean();
			sessionUserBean.setUser(userEntity);
			sessionUserBean.setDept(deptEntity);
			sessionUserBean.setWorkDept(deptEntity);
			sessionUserBean.setOrg(orgEntity);
			sessionUserBean.setWorkOrg(orgEntity);
			//提交督办单据
			this.executeSubmit(superviseEntity,mainTitle.toString(),sessionUserBean);
		}
	}

	/**
	 * @author: wudaliang, zhangjunyao
	 * @date: 2021-07-30, 2021-11-
	 * @description:
	 * @return: void
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void automaticSupervise() throws ParseException {
		// 查询超期项目
		List<Map<String, Object>> overDueProjects = getOverdueProject();
		// 查询超期里程碑及任务
		List<Map<String, Object>> overDueMilePosts = getOverdueMilePost();
		// 获取全部PMO各自管理的省区
		List<MpmPMOStandardizationRecordEntity> pmoEntities = pmoStandardizationRecordService.listAll();
		// 获取全部PMO的个人信息
        List<CboUserEntity> userEntities = getPmoInfo(pmoEntities);
        // 获取全部PMO的部门信息
        List<CboDeptEntity> deptEntities = getPmoDeptInfo(userEntities);
        // 获取全部PMO的组织信息
        List<CboOrgEntity> orgEntities = getPmoOrgInfo(deptEntities);
        // 转化为map类型
        Map<String, CboUserEntity> userMap = userEntities.stream().collect(Collectors.toMap(
                CboUserEntity::getCode, cboUserEntity -> cboUserEntity, (v1, v2) -> v1));
        Map<String, CboDeptEntity> deptMap = deptEntities.stream().collect(Collectors.toMap(
				s -> ConvertUtil.convertToString(s.getId()), cboDeptEntity -> cboDeptEntity, (v1, v2) -> v1));
        Map<String, CboOrgEntity> orgMap = orgEntities.stream().collect(Collectors.toMap(
                s -> ConvertUtil.convertToString(s.getId()), cboOrgEntity -> cboOrgEntity, (v1, v2) -> v1));
		// 日期加2天
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String format = simpleDateFormat.format(date);
		Date parse = simpleDateFormat.parse(format);
		Calendar instance = Calendar.getInstance();
		instance.setTime(parse);
		instance.add(Calendar.DAY_OF_YEAR,3);
		Date time = instance.getTime();
        // 处理超期项目
        setSuperviseForProjects(overDueProjects, pmoEntities, userMap, deptMap, orgMap, time);
		// 处理超期里程碑及任务
		setSuperviseForMilePost(overDueMilePosts, pmoEntities, userMap, deptMap, orgMap, time);
	}

	/**
	 * @author: houyuhang
	 * @date: 2021-09-06
	 * @param: mapRow
	 * @param: datacodeCache
	 * @description:重写setDispFields
	 * @return: void
	 * @modify:
	 */
	@Override
	public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
		super.setDispFields(mapRow, datacodeCache);
		String temp;
		String temp2;
		if (mapRow.get("supervisetype") != null) {
			temp = mapRow.get("supervisetype").toString();
			mapRow.put("dispsupervisetype", datacodeCache.getValueDynamic("MpmSuperviseType", temp, "code", "name"));
		}
		if (mapRow.get("superviseobjecttype") != null) {
			temp = mapRow.get("superviseobjecttype").toString();
			if (temp.contains(",")) {
				mapRow.put("dispsuperviseobjecttype", this.concatSuperviseObjectType(temp));
			} else {
				mapRow.put("dispsuperviseobjecttype", datacodeCache.getValueDynamic("MpmSuperviseObjectType", temp, "code", "name"));
			}
		}
		if (mapRow.get("superviseendstate") != null) {
			temp = mapRow.get("superviseendstate").toString();
			mapRow.put("dispsuperviseendstate", datacodeCache.getValueDynamic("MpmSuperviseEndState", temp, "code", "name"));
		}
		// 添加督办单状态
			if (mapRow.get("superviseendstate") != null) {
				mapRow.put("displiststate",  mapRow.get("dispsuperviseendstate"));
			} else {
				mapRow.put("dispListstate", mapRow.get("dispsupervisestate"));
			}
		if (mapRow.get("superviseobject") != null) {
			temp = mapRow.get("superviseobject").toString();
			temp2 = mapRow.get("superviseobjecttype").toString();
			if(StringUtil.isNumeric(temp)) {
				// 分为历史数据，自评，会议三种情况处理
				// 对于历史数据，其督办对象大类为其他 ‘0’
				if  ("0".equals(temp2)) {
					mapRow.put("dispsuperviseobject", datacodeCache.getValueDynamic("MpmSuperviseObject", temp, "code", "name"));
				} else if ("8".equals(temp2) || "16".equals(temp2)) {
					// 会议为 8 或16
					mapRow.put("dispsuperviseobject", datacodeCache.getValueDynamic("MpmMeetType", temp, "code", "name"));
				} else if ("7".equals(temp2)||"15".equals(temp2)) {
					// 自评为 7 或15
					mapRow.put("dispsuperviseobject", datacodeCache.getValueDynamic("MpmSelfBidScoreType", temp, "code", "name"));
				} else {
					mapRow.put("dispsuperviseobject", temp);
				}
			} else {
				mapRow.put("dispsuperviseobject", temp);
			}
		}
		//配置项目等级显示值
		if (mapRow.get("projectlevel") != null) {
			temp = mapRow.get("projectlevel").toString();
			mapRow.put("dispprojectlevel", datacodeCache.getValueDynamic("MpmProjectLevel", temp, "code", "name"));
		}
        // 部门显示值
		if (mapRow.get("deptcommoncode") != null) {
			temp = mapRow.get("deptcommoncode").toString();
			mapRow.put("dispdeptcommoncode", datacodeCache.getValueDynamic("DeptCommonCodeTrack", temp, "code", "name"));
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sendAppMessageToCcStaff(Map<String, Object> paraMap) {
		MpmProjectSuperviseEntity mpmProjectSuperviseEntity = queryById(ConvertUtil.convertToString(paraMap.get("id")));
		// 如果手动下发时没有选择抄送人，就不发消息。自动下发督办在开始节点无法指定抄送人，如果在PMO审核节点指定抄送人，会发送消息。
		if (mpmProjectSuperviseEntity.getCcstaffcode() != null) {
			// 督办单信息
			String title = "销售项目督办单提醒";
			String content = "【" + mpmProjectSuperviseEntity.getProjectname() + "】督办单:" +
					mpmProjectSuperviseEntity.getSupervisename() + "，已下发，责任人" +
					mpmProjectSuperviseEntity.getResponsiblename() + "，请知悉";
			// app信息处理
			ArrayList<Map<String, Object>> appMessageList = new ArrayList<>();
			List<String> ccStaffCodeList = Arrays.asList(mpmProjectSuperviseEntity.getCcstaffcode().split(","));
			for (String code : ccStaffCodeList) {
				Map<String, Object> appMessageMap = this.insertMessageApp(code, title, content,
						ConvertUtil.convertToLong(mpmProjectSuperviseEntity.getId()),
						MpmProjectSuperviseEntity.tableName, 0);
				appMessageList.add(appMessageMap);
			}
			// 发送信息
			cboMessageAppService = (ICboMessageAppService) SpringUtil.getBean("cboMessageAppService");
			cboMessageAppService.insertList(appMessageList);
		}
	}

	/**
	 *
	 * @description: 插入App消息
	 * @param
	 * @throws Exception
	 * @author: zhangqianbo
	 * @date:
	 * @modify:
	 */
	public Map<String, Object> insertMessageApp(String usercode, String extendfield1, String content, long sourceid, String sourcetype, int sendtype) {
		HashMap<String, Object> map = new HashMap<>();
		map.put("usercode", usercode);
		map.put("extendfield1", extendfield1);
		map.put("content", content);
		map.put("sourceid", sourceid);
		map.put("sourcetype", sourcetype);
		map.put("sendtype", sendtype);
		return map;
	}

	/**
	 * @author: zhangqianbo
	 * @date:
	 * @description: 插入系统消息
	 * @return: java.util.Map<java.lang.String, java.lang.Object>
	 * @modify:
	 */
	public Map<String, Object> insertMessageSys(String usercode, String username, String title, String content, long sourceid, String sourcetype) {
		HashMap<String, Object> map = new HashMap<>();
		map.put("receivercode", usercode);
		map.put("receivername", username);
		map.put("subject", title);
		map.put("content", content);
		map.put("sourceid", sourceid);
		map.put("sourcetype", sourcetype);
		return map;
	}
	/**
	 * @author: houyuhang
	 * @date:
	 * @description: 更新督办及mainititle信息
	 * @return: java.util.Map<java.lang.String, java.lang.Object>
	 * @modify:
	 */
	public void updateSuperviseUser(Map<String, Object> paraMap) {
		// 更新督办模块信息
		this.update(paraMap);
		// 更新maintitle
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目督办申请,单据编号{3}! ", paraMap.get("deptname"), paraMap.get("username"),
				DateUtil.dateToString(new Date(), "yyyy-MM-dd"), paraMap.get("docno"));
		// 更新flowins表的maintitle和extendFields3
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" sourceid = '{0}' and sourcetype = 'MpmProjectSupervise' and enabled = 1 ", paraMap.get("id"));
		CboApprovalFlowInsEntity cboApprovalFlowInsEntity = cboApprovalFlowInsService.queryObjectByWhere(sql.toString());
		if (ObjectUtil.isEmpty(cboApprovalFlowInsEntity)) {
			return;
		}
		cboApprovalFlowInsEntity.setMaintitle(mailtitle.toString());
		cboApprovalFlowInsEntity.setExtendfield3(ConvertUtil.convertToString(paraMap.get("usercode")));
		cboApprovalFlowInsService.updateEntity(cboApprovalFlowInsEntity);
		// 更新nodeins表的maintitle
		sql.clear();
		sql.appendSingle(" enabled = 1 and state = 1 and sourceid = '{0}' and sourcetype = 'MpmProjectSupervise' ", paraMap.get("id"));
		List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntities = cboApprovalNodeInsService.queryByWhere(sql.toString());
		if (CollectionUtil.isEmpty(cboApprovalNodeInsEntities)) {
			return;
		}
		List<BasicEntity> basicEntities = new ArrayList<>();
		for (CboApprovalNodeInsEntity cboApprovalNodeInsEntity : cboApprovalNodeInsEntities) {
			cboApprovalNodeInsEntity.setMaintitle(mailtitle.toString());
			basicEntities.add(cboApprovalNodeInsEntity);
		}
		cboApprovalNodeInsService.updateBatch(basicEntities);
	}
	/**
	 * @Title: deleteBefore
	 * @description: 删除督办时，如果有审批流程，同步删除
	 * @param whereSql
	 * @return
	 * @author: houyuhang
	 * @date: 2021年11月12日
	 * @modify:
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	protected void deleteBefore(String whereSql) {
		super.deleteBefore(whereSql);
		//找到删除的一条或多条督办
		List<MpmProjectSuperviseEntity> mpmProjectSuperviseEntities = this.queryByWhere(whereSql);
		if (CollectionUtil.isEmpty(mpmProjectSuperviseEntities)) {
			return;
		}
		// 如果删除了督办，需要同步删除督办关联的审批流程
		String taskStr = mpmProjectSuperviseEntities.stream().map(item -> ConvertUtil.convertToString(item.getId())).collect(Collectors.joining(","));
		if (StringUtil.isEmpty(taskStr)) {
			return;
		}
		// 删除flowins和nodeins表信息
		delCboApprovalInsInfo(MpmProjectSuperviseEntity.tableName, taskStr);
	}
        /**
         * @Description:    督办报表数据处理
         * @Author:         wuyuyang
         * @Return:         java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
         * @exception:
         * @Date:           20/3/2023 下午1:44
         * @Version:        1.0
         **/
		public List<Map<String, Object>> dealtWithData(List<Map<String, Object>> tempList) {
			DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
            if(tempList.size() == 0){
          		return tempList;
		    }
              // 数据处理
			List<Map<String, Object>> newTempList = new ArrayList<Map<String, Object>>();
            for (Map<String, Object> map : tempList) {
          	  // 处理响应状态
			  // 督办单据关闭
			 if (MpmSystemConst.SuperviseobjectType.TYPE_TWO.equals(ConvertUtil.convertToString(map.get("supervisestate")))){
				 if(MpmSystemConst.MpmSuperviseState.RESPOND_ONTIME.equals(ConvertUtil.convertToString(map.get("superviseendstate")))){
					 map.put("responsestatus", MpmSystemConst.ResponsestatusType.RESPOND_ON_TIME);
				 }else if(MpmSystemConst.MpmSuperviseState.DELAYED_RESPONSE.equals(ConvertUtil.convertToString(map.get("superviseendstate")))){
					 map.put("responsestatus", MpmSystemConst.ResponsestatusType.DELAYED_RESPONSE);
				 }else if(MpmSystemConst.MpmSuperviseState.NOT_RESPONDING.equals(ConvertUtil.convertToString(map.get("superviseendstate")))){
					 map.put("responsestatus", MpmSystemConst.ResponsestatusType.NOT_RESPONDING);
				 }else {
					 map.put("responsestatus", MpmSystemConst.ResponsestatusType.COMPLETED);
				 }
				 // 督办单据其他状态
			 } else {
				 SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
				 Date superviseperiod = (Date) map.get("superviseperiod");
				 Date now = new Date();
				 // 获取督办期限
				 Date tempForTime = null;
				 Date tempForNowTime = null;
				 String superviseperiodYmd = sdFormat.format(superviseperiod);
				 String nowYmd = sdFormat.format(now);
				 try{
					 tempForTime = sdFormat.parse(sdFormat.format(superviseperiod));
					 tempForNowTime = sdFormat.parse(sdFormat.format(now));
				 }catch (Exception e){
					 throw new ServiceException(e);
				 }
				 // 处理时间对比
				 int res = this.dealtWithDate(now, tempForTime);
				 if(superviseperiodYmd.equals(nowYmd)){
					 map.put("responsestatus",MpmSystemConst.ResponsestatusType.UNEXPIRED);
				 }else if(res == 0 || res == 1){
				 	map.put("responsestatus",MpmSystemConst.ResponsestatusType.UNEXPIRED);
				 } else {
				 	Calendar calendar = Calendar.getInstance();
				 	calendar.setTime(tempForTime);
				 	calendar.add(Calendar.DATE,3);
				 	String superviseperiodYmdNew = sdFormat.format(calendar.getTime());
				 	// 现在时间与督办期限三天后时间对比
				 	int resForLoading = this.dealtWithDate(now, calendar.getTime());
				 	if(superviseperiodYmdNew.equals(nowYmd)){
						map.put("responsestatus",MpmSystemConst.ResponsestatusType.EXCEED_THE_TIME_LIMIT);
					}else if(resForLoading == 0 || resForLoading ==1 ){
						map.put("responsestatus",MpmSystemConst.ResponsestatusType.EXCEED_THE_TIME_LIMIT);
					} else {
						map.put("responsestatus",MpmSystemConst.ResponsestatusType.EXTRA_NOT_RESPONDING);
					}
				 }
			 }
			 // 获取督办内容字段projectcontent
			 this.getProjectContentForStat(map);
			 newTempList.add(map);
		  }
			List<Map<String, Object>> resList = this.dealtWithCount(newTempList);
            // 处理被督办部门
            this.dealtWithResponsibleDept(resList);
			return resList;
		}
        /**
         * @Description:    处理被督办部门
         * @Author:         wuyuyang
         * @Return:         void
         * @exception:
         * @Date:           22/5/2023 下午10:12
         * @Version:        1.0
         **/
		private void dealtWithResponsibleDept(List<Map<String, Object>> resList) {
			DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
			StringBufferProxy userCodeSql = new StringBufferProxy();
			String resUserCodeSql;
			resList.stream().forEach(m -> {
				if (!ConvertUtil.convertToString(m.get("responsiblecode")).isEmpty()) {
					userCodeSql.appendSingle(ConvertUtil.convertToString("'" + m.get("responsiblecode")) + "',");
				}
			});
			if (ConvertUtil.convertToString(userCodeSql).isEmpty()) {
				return;
			}
			resUserCodeSql = "a.code in ("+ userCodeSql.toString().substring(0, userCodeSql.length() - 1) + ")";
			List<Map<String, Object>> resUserDeptList = this.queryMapByWhere(resUserCodeSql, "getUserDept");
			resList.stream().forEach(m -> {
				String tempCode = ConvertUtil.convertToString(m.get("responsiblecode"));
				if (!tempCode.isEmpty()) {
					resUserDeptList.stream().forEach(item -> {
						if (tempCode.equals(item.get("usercode"))) {
							m.put("responsibledeptcode", ConvertUtil.convertToString(item.get("deptcode")));
						}
					} );
				}
			});
			// 处理前台显示
			for (Map<String, Object> mapRow : resList) {
				String temp;
				if (mapRow.get("responsibledeptcode") != null) {
					// 研发本部展示二级部门，其他的展示一级部门
					temp = mapRow.get("responsibledeptcode").toString();
					// 获取研发本部编码集合
					String[] mpmRDDepartmentCodes = ParameterCache.getValue("MpmRDDepartmentCode").split(",");
					List<String> codeList = new ArrayList<>(Arrays.asList(mpmRDDepartmentCodes));
					for(String rdCode : codeList) {
						if (temp.startsWith(rdCode)) {
							if (temp.contains("_") && temp.length() > (temp.indexOf("_") + 5)) {
								// 例："D1F01_0101"
								temp = temp.substring(0, temp.indexOf("_") + 7);
								mapRow.put("dispresponsibledeptcode", datacodeCache.getValueDynamic("CboDept", temp, "code", "name"));
								// 221223
							} else if(!temp.contains("_") && temp.length() > 4){
								temp = temp.substring(0, 6);
								mapRow.put("dispresponsibledeptcode", datacodeCache.getValueDynamic("CboDept", temp, "code", "name"));
							} else {
								mapRow.put("dispresponsibledeptcode", datacodeCache.getValueDynamic("CboDept", temp, "code", "name"));
							}
						} else {
							// 获取一级部门
							String fullname = datacodeCache.getValueDynamic("CboDeptFull", temp, "code", "name");
							mapRow.put("dispresponsibledeptcode", fullname.split("\\\\")[1]);
							String resName = fullname.split("\\\\")[1];
							if (resName.contains(MpmSystemConst.Province_Name)) {
								resName = resName.replace(MpmSystemConst.Province_Name, "");
								mapRow.put("dispresponsibledeptcode", resName);
							}
						}
					}
				}
			}


		}


        /**
         * @Description:    比较时间
         * @Author:         wuyuyang
         * @Return:         int
         * @exception:
         * @Date:           21/3/2023 上午9:29
         * @Version:        1.0
         **/
		public int dealtWithDate(Date str1, Date str2 ) {
			Calendar time1 = Calendar.getInstance();
			Calendar time2 = Calendar.getInstance();
			time1.setTime(str1);
			time2.setTime(str2);
			// 比较时间
			if(time1.equals(time2)) {
				//相等
				return 0;
			}else if(time1.before(time2)){
				// 之前
				return 1;
			}else {
				// 之后
				return -1;
			}
		}
        /**
         * @Description:    处理督办单次数
         * @Author:         wuyuyang
         * @Return:         java.util.List<java.util.Map<javamp.lang.String,java.lang.Object>>
         * @exception:
         * @Date:           21/3/2023 上午10:53
         * @Version:        1.0
         **/
		public List<Map<String, Object>>  dealtWithCount(List<Map<String, Object>> newTempList) {
			DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
			if (newTempList.size() == 0) {
				return newTempList;
			}
			List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
			// 处理分页数据中的督办内容出现次数问题
			StringBufferProxy projectcodeList = new StringBufferProxy();
			for (Map<String, Object> map : newTempList) {
				String tempProjectcode = ConvertUtil.convertToString(map.get("projectcode"));
				if (!tempProjectcode.isEmpty()) {
					projectcodeList.appendSingle("'" + tempProjectcode + "'" + ",");
				}
			}
			String resProjectCodeList = projectcodeList.toString().substring(0, projectcodeList.length() - 1);
			StringBufferProxy sql = new StringBufferProxy();
			StringBufferProxy tempSql = new StringBufferProxy();
			// 处理数据超过1000的情况
			if (newTempList.size() > 1000) {
				String[] vedioPics = new String[newTempList.size()];
				for (Map<String, Object> mapForBigNum : newTempList) {
					String tempProjectcodeTemp = ConvertUtil.convertToString(mapForBigNum.get("projectcode"));
					if (!tempProjectcodeTemp.isEmpty()) {
						vedioPics = insert(vedioPics, tempProjectcodeTemp);
					}
				}
				String sqlWhere = this.spellSQLOfBigNum(vedioPics, "projectcode");
				sqlWhere = sqlWhere + "order by createon asc";
				sql.appendSingle(sqlWhere);
			} else {
				sql.appendSingle("projectcode in ({0}) order by createon asc", resProjectCodeList);
			}
			List<Map<String, Object>> list = this.queryMapByWhere(sql.toString(), "getCountForSupervise");
			for (Map<String, Object> map : list) {
				this.getProjectContentForStat(map);
			}
			List<Map<String, Object>> listForComp = new ArrayList<Map<String, Object>>();
			// 处理每页督办单据数据的次数
			for (Map<String, Object> map : newTempList) {
				String id = ConvertUtil.convertToString(map.get("id"));
				String projectcode = ConvertUtil.convertToString(map.get("projectcode"));
				String supervisetype = ConvertUtil.convertToString(map.get("supervisetype"));
				String superviseobjecttype = ConvertUtil.convertToString(map.get("superviseobjecttype"));
				String superviseobject = ConvertUtil.convertToString(map.get("superviseobject"));
				String superviseobjectcode = ConvertUtil.convertToString(map.get("superviseobjectcode"));
				String projectcontent = ConvertUtil.convertToString(map.get("projectcontent"));
				// 筛选相同督办内容的list
				if (!projectcontent.isEmpty() && !projectcode.isEmpty()) {
					listForComp = list.stream().filter(m -> projectcode.equals(ConvertUtil.convertToString(m.get("projectcode"))) &&
							projectcontent.equals(ConvertUtil.convertToString(m.get("projectcontent")))
					).collect(Collectors.toList());
					// 如果是里程碑或任务的督办，需要保证督办内容一致
					List<String> mileTaskContent = new ArrayList<>();
					mileTaskContent.add(MpmSystemConst.SuperviseContent.MILEPOST_OVERDUE);
					mileTaskContent.add(MpmSystemConst.SuperviseContent.MILEPOST_ALL);
					mileTaskContent.add(MpmSystemConst.SuperviseContent.TASK_OVERDUE);
					mileTaskContent.add(MpmSystemConst.SuperviseContent.TASK_ALL);
					if (mileTaskContent.contains(projectcontent)) {
						listForComp = listForComp.stream().filter(item -> superviseobjectcode.equals(ConvertUtil.convertToString(item.get("superviseobjectcode")))).collect(Collectors.toList());
						map.put("extramiletask", superviseobject);
					}
				}
				if (listForComp.size() > 0) {
						int i = 1;
						for (Map<String, Object> tempMap : listForComp) {
							if (id.equals(ConvertUtil.convertToString(tempMap.get("id")))) {
								map.put("supervisetime", "第" + ConvertUtil.convertToString(i) + "次");
								break;
							} else {
								i++;
							}
						}
					}
					// 处理响应时间
					if (MpmSystemConst.State.NOT_SUBMITTED.equals(map.get("state"))
							|| MpmSystemConst.State.APPROVAL_RETURN.equals(map.get("state"))) {
						map.put("responsetime", null);
					} else {
						String time = this.dealtWithResponseTime(id);
						map.put("responsetime", time);
					}
					resList.add(map);
				}
				return resList;
		   }
			/**
			 * @Description: 处理响应时间
			 * @Author: wuyuyang
			 * @Return: java.lang.String
			 * @exception:
			 * @Date: 21/3/2023 下午2:25
			 * @Version: 1.0
			 **/
			public String dealtWithResponseTime(String id){
				StringBufferProxy sql = new StringBufferProxy();
				sql.appendSingle("id = '{0}'", id);
				List<Map<String, Object>> responseTimelist = this.queryMapByWhere(sql.toString(), "getResponseTime");
				if (responseTimelist.size() == 0) {
					return "";
				} else {
					String time = ConvertUtil.convertToString(responseTimelist.get(0).get("approvaldate"));
					return time;
				}

			}

		public static String spellSQLOfBigNum(String[] fileidArr, String id) {
			StringBufferProxy whereSql = new StringBufferProxy();
			whereSql.appendSingle(" {0} in ( ", id);
			for (int i = 0; i < fileidArr.length; i++) {
				if (i % 999 == 0 && i > 0) {
					whereSql = whereSql.substring(0, whereSql.length() - 1);
					whereSql.appendSingle(" ) or {0} in ( '{1}',", id, fileidArr[i]);
				} else {
					whereSql.appendSingle("'{0}',", fileidArr[i]);
				}
			}
			whereSql = whereSql.substring(0, whereSql.length() - 1);
			whereSql.appendSingle(" )");
			return whereSql.toString();
		}

	//往字符串数组追加新数据
	private static String[] insert(String[] arr, String str) {
		int size = arr.length;  //获取数组长度
		String[] tmp = new String[size + 1];  //新建临时字符串数组，在原来基础上长度加一
		for (int i = 0; i < size; i++){  //先遍历将原来的字符串数组数据添加到临时字符串数组
			tmp[i] = arr[i];
		}
		tmp[size] = str;
		return tmp;
	}
	/**
	 * @Description: 拼接督办状态
	 * @Author: houyuhang
	 * @exception:
	 * @Date: 22/4/2023
	 * @Version: 1.0
	 **/
	public String concatSuperviseObjectType(String temp) {
		List<String> tempList = new ArrayList<>(Arrays.asList(temp.split(",")));
		return tempList.stream().map(item -> datacodeCache.getValueDynamic("MpmSuperviseObjectType", item, "code", "name")).collect(Collectors.joining(","));
	}
	/**
	 * @Description: 督办报表
	 * @Author: houyuhang
	 * @exception:
	 * @Date: 2023/4/22
	 * @Version: 1.0
	 **/
	public void getProjectContentForStat(Map<String, Object> map) {
		// 督办单类型
		String supervisetype = ConvertUtil.convertToString(map.get("supervisetype"));
		if (supervisetype.isEmpty()) {
			supervisetype = "0";
		}
		// 督办大类
		String superviseobjecttype = ConvertUtil.convertToString(map.get("superviseobjecttype"));
		// 督办小类
		String superviseobject = ConvertUtil.convertToString(map.get("superviseobject"));
		// 如果督办大类为多选，督办内容解析为用逗号分隔
		if (superviseobjecttype.contains(",")) {
			map.put("projectcontent", this.concatSuperviseObjectTypeForStat(superviseobjecttype));
		} else {
			if(superviseobject.isEmpty()){
				superviseobject = "";
			}else if(
					(MpmSystemConst.SuperviseObjecttypeType.TYPE_EIGHT.equals(superviseobjecttype)
							|| MpmSystemConst.SuperviseObjecttypeType.TYPE_SEVEN.equals(superviseobjecttype)
							|| MpmSystemConst.SuperviseObjecttypeType.TYPE_FIFTH.equals(superviseobjecttype)
							|| MpmSystemConst.SuperviseObjecttypeType.TYPE_SIXTH .equals(superviseobjecttype)) &&
							MpmSystemConst.SuperviseObjecttypeCompare.List.contains("," + superviseobject + ",")){
				// 不做任何操作
			}else{
				superviseobject = "";
			}
			// 处理督办内容
			String projectcontent = supervisetype + "-" + superviseobjecttype;
			if(!superviseobject.isEmpty()){
				projectcontent = projectcontent + "-" + superviseobject;
			}
			map.put("projectcontent", datacodeCache.getValueDynamic("MpmSuperviseContent", projectcontent, "code", "name"));
		}
	}
    /**
     * @Description: 拼接督办报表-督办内容
     * @Author: houyuhang
     * @exception:
     * @Date: 22/4/2023
     * @Version: 1.0
     **/
    public String concatSuperviseObjectTypeForStat(String temp) {
        List<String> tempList = new ArrayList<>(Arrays.asList(temp.split(",")));
        // 如果拼接的字段没有超期且不是其他，拼接上问题两个字
        return tempList.stream().map(item -> datacodeCache.getValueDynamic("MpmSuperviseObjectType", item, "code", "name"))
                .map(item -> item.contains("超期") || item.contains("其他") ? item : item + "问题").collect(Collectors.joining(","));
    }
}
